<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 商户管理
 *
 * @icon fa fa-circle-o
 */
class Litestoreshop extends Backend
{
    
    /**
     * Litestoreshop模型对象
     * @var \app\admin\model\Litestoreshop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Litestoreshop;
        $this->view->assign("statusList", $this->model->getStatusList());

        $this->user_model= new \app\admin\model\User;

        //标签数组
        $this->tag_model = new \app\admin\model\litestore\Tag;
        $list = $this->tag_model->select();
        $tags = [];
        foreach ($list as $value) {
            $tags[$value['id']] = $value['tagname'];
        }
        $this->view->assign("tagList", $tags);

        //推荐位数组
        $this->posid_model = new \app\admin\model\litestore\Posid;
        $list = $this->posid_model->select();
        $posids = [];
        foreach ($list as $value) {
            $posids[$value['id']] = $value['posidname'];
        }
        $this->view->assign("posidList", $posids);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['shopcategory','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['shopcategory','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                $row->getRelation('shopcategory')->visible(['name']);
				$row->getRelation('user')->visible(['username','nickname']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }



                    $result = $this->model->allowField(true)->insertGetId($params);

                    if ($result !== false) {

                        $ids = $result;
                        //管理标签
                        $tags = $this->request->post("tags/a");
                        $this->tag_model->add_tags($ids,$tags);
                        //推荐位管理
                        $posids = $this->request->post("posids/a");
                        $this->posid_model->add_posids($ids,$posids);

                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }

                    //管理标签
                    $tags = $this->request->post("tags/a");
                    $this->tag_model->edit_tags($ids,$tags);
                    //推荐位管理
                    $posids = $this->request->post("posids/a");
                    $this->posid_model->edit_posids($ids,$posids);
                    //如果审核通过，把申请人代理字段变为1
                    if($params['status']==1){
                        $shop_status=1;
                    }else{
                        $shop_status=0;
                    }
                    $this->user_model->where('id',$params['user_id'])->update(['is_shop'=>$shop_status]);


                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        //商户标签
        $shoptags = $this->tag_model->shop_tags_id($ids);
        $this->view->assign("shoptags", $shoptags);

        //商户推荐位
        $shopposids = $this->posid_model->shop_posids_id($ids);
        $this->view->assign("shopposids", $shopposids);


        return $this->view->fetch();
    }


}
